package MicroSpring.common;

import MicroSpring.beanFactory.impl.BeanDefinition;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class BeanDefinitionSortUtils {

    public static TreeMap<BeanNameSort, BeanDefinition> sortBeansDefinitions(Map<String, BeanDefinition> beanDefinitionMap) {
        TreeMap<BeanNameSort,BeanDefinition>beanNameSortTreeMap=new TreeMap<>(new BeanNameComparator());
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            BeanDefinition definition = entry.getValue();
            String beanName = entry.getKey();
            BeanNameSort sort=new BeanNameSort();
            sort.setBeanName(beanName);
            sort.setLevel(definition.getLevel());
            beanNameSortTreeMap.put(sort,definition);
        }
        return beanNameSortTreeMap;
    }
    private static class BeanNameComparator  implements Comparator<BeanNameSort>{
        @Override
        public int compare(BeanNameSort o1, BeanNameSort o2) {
            return o2.getLevel()-o1.getLevel();
        }
    }

    public static class BeanNameSort {
        private String beanName;
        private int level=0; //层级越大,说明优先级越高

        public String getBeanName() {
            return beanName;
        }

        public void setBeanName(String beanName) {
            this.beanName = beanName;
        }

        public int getLevel() {
            return level;
        }

        public void setLevel(int level) {
            this.level = level;
        }
    }

    public static void main(String[] args) {
        TreeMap<BeanNameSort,String>testmp=new TreeMap<>(new BeanNameComparator());
        BeanNameSort s1=new BeanNameSort();
        s1.setBeanName("s1");
        s1.setLevel(1);
        BeanNameSort s2=new BeanNameSort();
        s2.setBeanName("s2");
        s2.setLevel(2);
        BeanNameSort s3=new BeanNameSort();
        s3.setBeanName("s3");
        s3.setLevel(3);

        testmp.put(s1,"v1");
        testmp.put(s2,"v2");
        testmp.put(s3,"v3");

        for (Map.Entry<BeanNameSort, String> entry : testmp.entrySet()) {
            System.out.println(entry.getKey()+" : "+entry.getValue());
        }

    }
}
